package com.hrhx.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.thoughtworks.xstream.XStream;
/**
 *  新增设置头信息：
	private static final String XML_HEAD_STR = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	
	Google浏览器插件-XML Tree
	Displays XML data in a user friendly way.
	
	//如果中文返回出现？？字符
	response.setCharacterEncoding("UTF-8");
	
	//如果返回的中文是“烇湫”这种乱码，说明浏览器的解析问题
	response.setHeader("Content-type", "text/xml;charset=UTF-8");
 * @author duhongming
 *
 */
public class XmlUtil {
	private static final String XML_HEAD_STR = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	private static XmlUtil instance = null;
	private XStream xs = null;

	private XmlUtil() {
		this.xs = new XStream();
	}

	/**
	 * 初始化XmlUtil
	 * @return
	 */
	public static synchronized XmlUtil getInstance() {
		if (instance == null) {
			System.out.println("正在初始化XML处理对象.............");
			instance = new XmlUtil();
		}

		return instance;
	}

	/**
	 * 将Object转化为XML字符串
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public String toXML(Object obj) throws Exception {
		if (obj == null) {
			return null;
		}
		return XML_HEAD_STR+'\n'+this.xs.toXML(obj);
	}
	
	/**
	 * 对toXML方法重载，修改<节点名称>
	 * @param obj
	 * @param aliasMap
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public String toXML(Object obj,Map<String,Class> aliasMap) throws Exception {
		if (obj == null) {
			return null;
		}
		for(Map.Entry<String, Class> entry:aliasMap.entrySet()){    
			this.xs.alias(entry.getKey(), entry.getValue()); 
		}   
		return XML_HEAD_STR+'\n'+this.xs.toXML(obj);
	}

	/**
	 * 将Object转化为XML文件
	 * @param obj
	 * @param strFile
	 * @throws Exception
	 */
	public void toXMLFile(Object obj, String strFile) throws Exception {
		if (obj == null) {
			return;
		}
		if ((strFile == null) || ("".equals(strFile))) {
			throw new Exception("XML保存的文件名不能为空！");
		}
		String str = strFile;
		str = str.replaceAll("//", "/");

		File f = new File(str.substring(0, str.lastIndexOf("/")));
		if (!f.exists()) {
			f.mkdirs();
		}
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(new File(str));
			this.xs.toXML(obj, fos);
			fos.close();
		} catch (Exception e) {
			if (fos != null){
				fos.close();
			}
			e.printStackTrace();
			throw new Exception("将对象写到文件" + str + "失败！" + e.getMessage());
		}
	}

	/**
	 * 将XML字符串转成Object
	 * @param xml
	 * @return
	 * @throws Exception
	 */
	public Object fromXML(String xml) throws Exception {
		if ((xml == null) || ("".equals(xml))) {
			return null;
		}

		return this.xs.fromXML(xml);
	}

	/**
	 * 将XML文件转成Object
	 * @param strFile
	 * @return
	 * @throws Exception
	 */
	public Object fromXMLFile(String strFile) throws Exception {
		if ((strFile == null) || ("".equals(strFile))) {
			return null;
		}
		FileInputStream fis = null;
		Object obj = null;
		String str = strFile;
		str = str.replaceAll("//", "/");
		File f = new File(str);
		if (!f.exists()) {
			return null;
		}
		try {
			fis = new FileInputStream(f);
			obj = this.xs.fromXML(fis);
			fis.close();
		} catch (Exception e) {
			if (fis != null) {
				fis.close();
			}
			e.printStackTrace();
			throw new Exception("从文件" + str + "读取内容进行对象转换时失败！" + e.getMessage());
		}
		return obj;
	}

	public static void main(String[] args) throws Exception {
		String begin = "2002-10-21 23:12:34";
		begin = begin.substring(5, 7) + "月" + begin.substring(8, 10) + "日";
		List<String> list = new ArrayList<String>();
		list.add("duhongming");
		list.add("24");
		list.add(begin);
		String listXml = getInstance().toXML(list);
		System.out.println("将List数据转成XML："+listXml);
		System.out.println("将XML数据转成List："+getInstance().fromXML(listXml));
		
	    String templateFileName = System.getProperty("user.dir")+"/target/demo.xml";
	    getInstance().toXMLFile(list, templateFileName);
		System.out.println("将XML文件数据转成List："+getInstance().fromXMLFile(templateFileName));
		
		Map<String,String> map = new HashMap<String,String>(16);
		map.put("name", "duhongming");
		map.put("age", "24");
		map.put("birthday", "7月26日");
		String mapXml = getInstance().toXML(map);
		System.out.println("将Map数据转成XML："+mapXml);
		System.out.println(("将XML数据转成Map："+getInstance().fromXML(mapXml)));
	}
}
